package com.zt.questionnaire.common.typehandler;

import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedHashMap;

/**
 * 有序的map，从数据库反序列化以后也是有序的
 */
public class EntityJsonLinkedHashMapTypeHandler extends BaseTypeHandler<LinkedHashMap> {

	private String toJson(LinkedHashMap map) {
		try {
			return JSONObject.toJSONString(map);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private LinkedHashMap toObject(String content) {
		if (content != null && !content.isEmpty()) {
			try {
				return JSONObject.parseObject(content, LinkedHashMap.class);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		} else {
			return null;
		}
	}

	@Override
	public LinkedHashMap getNullableResult(ResultSet rs, String paramString) throws SQLException {
		//查询是起作用
		return this.toObject(rs.getString(paramString));
	}

	@Override
	public LinkedHashMap getNullableResult(ResultSet rs, int paramInt) throws SQLException {
		return this.toObject(rs.getString(paramInt));
	}

	@Override
	public LinkedHashMap getNullableResult(CallableStatement cs, int paramInt) throws SQLException {
		return this.toObject(cs.getString(paramInt));
	}

	@Override
	public void setNonNullParameter(PreparedStatement ps, int paramInt, LinkedHashMap paramT,
			JdbcType paramJdbcType) throws SQLException {
		//insert时起作用
		ps.setString(paramInt, this.toJson(paramT));
	}
}
